<template>
    <section class="experiment">
      <!-- <div class="make-center"> -->
        <input type="text" id="broadcast-id" placeholder="broadcast-id" value="room-xyz" style="display:none">
          <button id="open-or-join" @click="openorjoin" v-show="buttonShow">开始直播</button>
          <!-- <div id="room-urls" style="text-align: center;display: none;background: #F1EDED;margin: 15px -10px;border: 1px solid rgb(189, 189, 189);border-left: 0;border-right: 0;"></div> -->
        <!-- </div> -->
      <!-- <div class="make-center" id="broadcast-viewers-counter"></div> -->
      <video id="video-preview" controls="" loop="" v-show="videoShow"></video>
      <!-- <p @click="click">click me</p> -->
    </section>
  </template>
  <script>
    var enableRecordings = false;
    var connection = new RTCMultiConnection(null, {
    useDefaultDevices: true // if we don't need to force selection of specific devices
    });
    connection.enableScalableBroadcast = true;
    connection.maxRelayLimitPerUser = 1;
    connection.autoCloseEntireSession = true;
    connection.socketURL = 'https://www.allbim.cn/';
    connection.socketMessageEvent = 'scalable-media-broadcast-demo';
    export default {
    props:['bcid'],
    data() {
    return {
      buttonShow:true,
      videoShow:false,
      broadcastId:this.bcid
    }
    },
    methods: {
        // 更改直播状态
        changeStatus(broadcastId,status) {
            let obj = {
                id: broadcastId,
                status: status,
            }
            this.$api.post(this.$api.baseURLSchool,"update_live_room/edit",obj,r => {
                console.log(r);
                if(r.data.ret == 1) {
                }
            },err => {
                console.log(err);
            })
        },
      click:function(){
        alert("这是传过来的userId:"+this.bcid);
        // alert("这是接收的userId:"+this.broadcastId);
  
      },
    callbackFn:function(bcid){
        var _this = this;
        var broadcastId= bcid;
        // alert("这是房间号："+broadcastId);
        // alert(typeof this.bcid);
      //   alert("callbackfn内的broadcastId："+broadcastId);
  
        document.getElementById('open-or-join').disabled = true;
  
        connection.session = {
        audio: true,
        video: true,
        oneway: true
        };
  
        var socket = connection.getSocket();
  
        socket.emit('check-broadcast-presence', broadcastId, function(isBroadcastExists) {
        if(!isBroadcastExists) {
        // the first person (i.e. real-broadcaster) MUST set his user-id
            connection.userid = broadcastId;
        } else {
            _this.changeStatus(broadcastId,1);
        }
  
        console.log('check-broadcast-presence', broadcastId, isBroadcastExists);
        
        socket.emit('join-broadcast', {
        broadcastId: broadcastId,
        userid: connection.userid,
        typeOfStreams: connection.session
        });
        });
        },
    openorjoin:function(){
        if(this.bcid == null || this.bcid == '') {
            this.$utils._toast('房间号不可为空');
            return false;
        }
        this.buttonShow=false;
        this.videoShow=true;
        alert(this.bcid);
      app.checkAndroidPermissions(this.callbackFn(this.bcid));
    }
    },
    created() {
    },
    //history模式下 返回会触发
    beforeRouteEnter(to, from, next) {
    next();
    },
    beforeRouteLeave(to, from, next) {
    next();
    },
    //history模式下 返回会触发
    activated() {
    // console.log(localStorage.getItem("scrollTop"));
    if(localStorage.getItem("scrollTop")) {
    $('section').scrollTop(localStorage.getItem("scrollTop"));
    }
    },
    mounted() {
    connection.connectSocket(function(socket) {
    // this event is emitted when a broadcast is already created.
    socket.on('join-broadcaster', function(hintsToJoinBroadcast) {
    console.log('join-broadcaster', hintsToJoinBroadcast);
  
    connection.session = hintsToJoinBroadcast.typeOfStreams;
    connection.sdpConstraints.mandatory = {
    OfferToReceiveVideo: !!connection.session.video,
    OfferToReceiveAudio: !!connection.session.audio
    };
    connection.broadcastId = hintsToJoinBroadcast.broadcastId;
    connection.join(hintsToJoinBroadcast.userid);
    });
  
    socket.on('rejoin-broadcast', function(broadcastId) {
    console.log('rejoin-broadcast', broadcastId);
  
    connection.attachStreams = [];
    socket.emit('check-broadcast-presence', broadcastId, function(isBroadcastExists) {
    if(!isBroadcastExists) {
    // the first person (i.e. real-broadcaster) MUST set his user-id
    connection.userid = broadcastId;
    }
  
    socket.emit('join-broadcast', {
    broadcastId: broadcastId,
    userid: connection.userid,
    typeOfStreams: connection.session
    });
    });
    });
  
    socket.on('broadcast-stopped', function(broadcastId) {
    // alert('Broadcast has been stopped.');
    // location.reload();
    console.error('broadcast-stopped', broadcastId);
    alert('This broadcast has been stopped.');
    });
  
    // this event is emitted when a broadcast is absent.
    socket.on('start-broadcasting', function(typeOfStreams) {
    console.log('start-broadcasting', typeOfStreams);
  
    // host i.e. sender should always use this!
    connection.sdpConstraints.mandatory = {
    OfferToReceiveVideo: false,
    OfferToReceiveAudio: false
    };
    connection.session = typeOfStreams;
  
    // "open" method here will capture media-stream
    // we can skip this function always; it is totally optional here.
    // we can use "connection.getUserMediaHandler" instead
    connection.open(connection.userid, function() {
    showRoomURL(connection.sessionid);
    });
    });
    });
    var videoPreview = document.getElementById('video-preview');
    connection.onstream = function(event) {
    if(connection.isInitiator && event.type !== 'local') {
          return;
          }
  
          if(event.mediaElement) {
          event.mediaElement.pause();
          delete event.mediaElement;
          }
          connection.isUpperUserLeft = false;
          videoPreview.src = URL.createObjectURL(event.stream);
          videoPreview.play();
  
          videoPreview.userid = event.userid;
  
          if(event.type === 'local') {
          videoPreview.muted = true;
          }
  
          if (connection.isInitiator == false && event.type === 'remote') {
          // he is merely relaying the media
          connection.dontCaptureUserMedia = true;
          connection.attachStreams = [event.stream];
          connection.sdpConstraints.mandatory = {
          OfferToReceiveAudio: false,
          OfferToReceiveVideo: false
          };
  
          var socket = connection.getSocket();
          socket.emit('can-relay-broadcast');
  
          if(connection.DetectRTC.browser.name === 'Chrome') {
          connection.getAllParticipants().forEach(function(p) {
          if(p + '' != event.userid + '') {
          var peer = connection.peers[p].peer;
          peer.getLocalStreams().forEach(function(localStream) {
          peer.removeStream(localStream);
          });
          peer.addStream(event.stream);
          connection.dontAttachStream = true;
          connection.renegotiate(p);
          connection.dontAttachStream = false;
          }
          });
          }
  
          if(connection.DetectRTC.browser.name === 'Firefox') {
          // Firefox is NOT supporting removeStream method
          // that's why using alternative hack.
          // NOTE: Firefox seems unable to replace-tracks of the remote-media-stream
          // need to ask all deeper nodes to rejoin
          connection.getAllParticipants().forEach(function(p) {
          if(p + '' != event.userid + '') {
          connection.replaceTrack(event.stream, p);
          }
          });
          }
  
          // Firefox seems UN_ABLE to record remote MediaStream
          // WebAudio solution merely records audio
          // so recording is skipped for Firefox.
          if(connection.DetectRTC.browser.name === 'Chrome') {
          repeatedlyRecordStream(event.stream);
          }
          }
          };
          connection.onstreamended = function() {};
  
          connection.onleave = function(event) {
              if(event.userid !== videoPreview.userid) return;
  
              var socket = connection.getSocket();
              socket.emit('can-not-relay-broadcast');
  
              connection.isUpperUserLeft = true;
  
              if(allRecordedBlobs.length) {
                  // playing lats recorded blob
                  var lastBlob = allRecordedBlobs[allRecordedBlobs.length - 1];
                  videoPreview.src = URL.createObjectURL(lastBlob);
                  videoPreview.play();
                  allRecordedBlobs = [];
              }
              else if(connection.currentRecorder) {
                  var recorder = connection.currentRecorder;
                  connection.currentRecorder = null;
                  recorder.stopRecording(function() {
                      if(!connection.isUpperUserLeft) return;
  
                      videoPreview.src = URL.createObjectURL(recorder.blob);
                      videoPreview.play();
                  });
              }
  
              if(connection.currentRecorder) {
                  connection.currentRecorder.stopRecording();
                  connection.currentRecorder = null;
              }
          };
          var allRecordedBlobs = [];
  
          function repeatedlyRecordStream(stream) {
          if(!enableRecordings) {
          return;
          }
  
          connection.currentRecorder = RecordRTC(stream, {
          type: 'video'
          });
  
          connection.currentRecorder.startRecording();
  
          setTimeout(function() {
          if(connection.isUpperUserLeft || !connection.currentRecorder) {
          return;
          }
  
          connection.currentRecorder.stopRecording(function() {
          allRecordedBlobs.push(connection.currentRecorder.blob);
  
          if(connection.isUpperUserLeft) {
          return;
          }
  
          connection.currentRecorder = null;
          repeatedlyRecordStream(stream);
          });
          }, 30 * 1000); // 30-seconds
          };
  
          function disableInputButtons() {
            document.getElementById('open-or-join').disabled = true;
            document.getElementById('broadcast-id').disabled = true;
          }
          // below section detects how many users are viewing your broadcast
  
          connection.onNumberOfBroadcastViewersUpdated = function(event) {
          if (!connection.isInitiator) return;
  
          document.getElementById('broadcast-viewers-counter').innerHTML = '当前观看人数: <b>' + event.numberOfBroadcastViewers + '</b>';
          };
          }
          }
        </script>
  <style lang="scss">
  .experiment{
    position: absolute;
    top: 0;
    width: 100%;
    height: 100%;
  }
  #open-or-join{
      width: 144px;
      background: linear-gradient(to bottom, #43d88a, #43d89c);;
      color: #fff;
      height: 35px;
      font-size: 17px;
      border-radius: 16px;
      text-align: center;
      border: none;
      position: absolute;
      bottom: 10%;
      left: 50%;
      transform: translateX(-50%);
  }
    video {
    object-fit: fill;
    width: 100%;
    max-width: 100%;
    height: 100%;
    }
    input,
    select {
    font-weight: normal;
    padding: 2px 4px;
    text-decoration: none;
    display: inline-block;
    text-shadow: none;
    font-size: 16px;
    outline: none;
    }
  
    .make-center {
    text-align: center;
    // padding: 5px 10px;
    }
  
    input, select {
    font-family: Myriad, Arial, Verdana;
    font-weight: normal;
    border-top-left-radius: 3px;
    border-top-right-radius: 3px;
    border-bottom-right-radius: 3px;
    border-bottom-left-radius: 3px;
    padding: 4px 12px;
    text-decoration: none;
    color: rgb(27, 26, 26);
    display: inline-block;
    box-shadow: rgb(255, 255, 255) 1px 1px 0px 0px inset;
    text-shadow: none;
    background: -webkit-gradient(linear, 0% 0%, 0% 100%, color-stop(0.05, rgb(241, 241, 241)), to(rgb(230, 230, 230)));
    font-size: 20px;
    border: 1px solid red;
    outline:none;
    vertical-align: middle;
    }
    select {
    height: 35px;
    margin: 0 5px;
    }
  
     input:hover, select:hover {
    background: -webkit-gradient(linear, 0% 0%, 0% 100%, color-stop(5%, rgb(221, 221, 221)), to(rgb(250, 250, 250)));
    border: 1px solid rgb(142, 142, 142);
    }
  
    input:active, select:active, input:focus, select:focus {
    background: -webkit-gradient(linear, 0% 0%, 0% 100%, color-stop(5%, rgb(183, 183, 183)), to(rgb(255, 255, 255)));
    border: 1px solid rgb(142, 142, 142);
    }
    iput[disabled], select[disabled] {
    background: rgb(249, 249, 249);
    border: 1px solid rgb(218, 207, 207);
    color: rgb(197, 189, 189);
    }
    input, input:focus, input:active {
    background: white;
    }
  </style>
  